# tools/audisp-gmseal/Makefile.am

bin_PROGRAMS = audisp-gmseal

audisp_gmseal_SOURCES = gmseal-plugin.c $(top_builddir)/lib/gm_crypto.c
audisp_gmseal_LDADD   = $(top_builddir)/lib/.libs/libaudit.so -lcrypto -lcap
audisp_gmseal_CFLAGS  = -I$(top_srcdir)/lib -D_GNU_SOURCE

# 模板随源码分发，由 configure 用 @bindir@ 展开生成 gmseal.conf
EXTRA_DIST = gmseal.conf.in
CLEANFILES = gmseal.conf

# 目录约定
etc_plugin_confdir = /etc/audit/plugins.d
alt_plugin_confdir = $(sysconfdir)/audit/plugins.d
pkgdatadir_local   = $(datadir)/audisp-gmseal
tmpfiles_dir       = /usr/lib/tmpfiles.d

# 说明：
# gmseal.conf 由 configure（AC_CONFIG_FILES）生成在 $(builddir)
# 我们安装时：
#   1) 永久在 $(datadir)/audisp-gmseal/ 放一份模板副本（便于回滚/对比）
#   2) 优先把文件安装到 /etc/audit/plugins.d/gmseal.conf（不存在时才写入）
#   3) 若受策略限制写不了 /etc，则退回 $(sysconfdir) 并安装一个 tmpfiles 规则
install-data-hook: $(builddir)/gmseal.conf
	@set -e; \
	: # 1) 模板副本 -> 数据目录; \
	$(MKDIR_P) "$(DESTDIR)$(pkgdatadir_local)"; \
	$(INSTALL_DATA) -m 640 "$(builddir)/gmseal.conf" "$(DESTDIR)$(pkgdatadir_local)/gmseal.conf"; \
	: # 2) 首选：写 /etc; \
	d="$(DESTDIR)$(etc_plugin_confdir)"; f="gmseal.conf"; \
	echo "==> Trying to install to $$d/$$f (preferred)"; \
	if $(MKDIR_P) "$$d" 2>/dev/null && test -d "$$d" && test -w "$$d"; then \
	  if test -f "$$d/$$f"; then \
	    echo "Preserving existing $$d/$$f (not overwriting)"; \
	  else \
	    echo "Installing $$d/$$f"; \
	    $(INSTALL_DATA) -m 640 "$(DESTDIR)$(pkgdatadir_local)/gmseal.conf" "$$d/$$f"; \
	    if command -v restorecon >/dev/null 2>&1; then restorecon -Fv "$$d/$$f" >/dev/null 2>&1 || true; fi; \
	  fi; \
	else \
	  echo "WARN: cannot write $$d (policy). Falling back to tmpfiles + alt dir..."; \
	  : # 3) 退路：在 $(sysconfdir) 放一份，便于人工查看; \
	  d2="$(DESTDIR)$(alt_plugin_confdir)"; \
	  $(MKDIR_P) "$$d2"; \
	  if test -f "$$d2/$$f"; then \
	    echo "Preserving existing $$d2/$$f (not overwriting)"; \
	  else \
	    echo "Installing $$d2/$$f (fallback)"; \
	    $(INSTALL_DATA) -m 640 "$(DESTDIR)$(pkgdatadir_local)/gmseal.conf" "$$d2/$$f"; \
	  fi; \
	  : # 4) 安装 tmpfiles 规则，由 systemd-tmpfiles 复制到 /etc; \
	  $(MKDIR_P) "$(DESTDIR)$(tmpfiles_dir)"; \
	  tf="$(DESTDIR)$(tmpfiles_dir)/audisp-gmseal.conf"; \
	  printf "C %s/%s 0640 root root - %s/gmseal.conf\n" "$(etc_plugin_confdir)" "$$f" "$(pkgdatadir_local)" > "$$tf"; \
	  if command -v systemd-tmpfiles >/dev/null 2>&1; then \
	    echo "==> Running systemd-tmpfiles to materialize /etc copy"; \
	    systemd-tmpfiles --create "$$tf" >/dev/null 2>&1 || true; \
	  fi; \
	fi

uninstall-local:
	@rm -f '$(DESTDIR)$(alt_plugin_confdir)/gmseal.conf' 2>/dev/null || true; \
	 rm -f '$(DESTDIR)$(pkgdatadir_local)/gmseal.conf' 2>/dev/null || true; \
	 rm -f '$(DESTDIR)$(tmpfiles_dir)/audisp-gmseal.conf' 2>/dev/null || true
